package cn.new18.testactivitytask.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;

import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.new18.testactivitytask.R;
import cn.new18.testactivitytask.bean.Student;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by RaoWei on 2017/2/15 10:03.
 */

public class RxAndroidTest extends Activity {

    @BindView(R.id.rx_tv1)
    TextView mRxTv1;
    private String Tag = this.getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_rx);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //ReadImgTest();
        //startRxJava1();
        //startRxJava2();
        //startRxJava3();
        //startRxJava4();
        //startRxJava5();
        //startRxJava6();
        //startRxJava7();
        startRxJava8();
    }

    /**
     * 线程切换
     */
    private void startRxJava8() {
        Observable.just(1,2,3,4)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .map(new Func1<Integer, String>() {
                    @Override
                    public String call(Integer integer) {
                        Log.e(Tag, "我是第一个map： " + integer + ", 线程： " + Thread.currentThread().getName());
                        return "i`am " + integer;
                    }
                })
                .observeOn(Schedulers.io())
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        Log.e(Tag, "我是第二个map: " + s + ", 线程： " + Thread.currentThread().getName());
                        return s;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        Log.e(Tag, "subscriber: " + s + ", 线程： " + Thread.currentThread().getName());

                    }
                });
    }

    private void startRxJava7() {
        //在每次事件触发后的一定时间间隔内丢弃新的事件
        RxView.clicks(new Button(this)).throttleFirst(500, TimeUnit.MILLISECONDS);
    }


    /**
     * flatMap() 一对多变换
     */
    private void startRxJava6() {
        final Student[] students = {new Student()};
        Observable.from(students)
                .subscribe(new Action1<Student>() {
                    @Override
                    public void call(Student student) {
                        ArrayList<Student.Course> courses = student.getCourses();
                        for (int i = 0; i < courses.size(); i++) {
                            Log.e(Tag , courses.get(i).getName());
                        }

                    }
                });

        Observable.from(students)
                .flatMap(new Func1<Student, Observable<Student.Course>>() {
                    @Override
                    public Observable<Student.Course> call(Student student) {
                        return Observable.from(student.getCourses());
                    }
                })
                .subscribe(new Action1<Student.Course>() {
                    @Override
                    public void call(Student.Course course) {
                        Log.e(Tag, course.getName());
                    }
                });
    }

    //map() funx()
    private void startRxJava5() {
        Observable.just("images/logo.png")
                .map(new Func1<String, Bitmap>() {  //FuncX：X参1个返回值;map()一对一的转换
                    @Override
                    public Bitmap call(String s) {
                        return getBimapFromFile(new File(s));
                    }
                })
                .subscribe(new Action1<Bitmap>() {
                    @Override
                    public void call(Bitmap bitmap) {
                        //得到bitmap
                    }
                });
    }

    //b. 由 id 取得图片并显示
    private void startRxJava4() {
        final int drawableRes = -1;
        final ImageView imageView = new ImageView(this);
        Observable.create(new Observable.OnSubscribe<Drawable>() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void call(Subscriber<? super Drawable> subscriber) {
                Drawable drawable = getTheme().getDrawable(drawableRes);
                subscriber.onNext(drawable);
                subscriber.onCompleted();
            }
        })
                .subscribeOn(Schedulers.io())  //指定subscrible()发生在IO线程
                .observeOn(AndroidSchedulers.mainThread())  //指定subscriber的回调发生在主线程
                .subscribe(new Observer<Drawable>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                Toast.makeText(RxAndroidTest.this, "Error!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(Drawable drawable) {
                imageView.setImageDrawable(drawable);
            }
        });

    }

    //a. 打印字符串数组
    private void startRxJava3() {
        String[] names = {"RxJava", "RxAndroid", "RxGolang", "RxJavascript"};
        Observable.from(names)
            .subscribe(new Action1<String>() {
                @Override
                public void call(String s) {
                    Log.e(Tag, s);
                }
            });
    }

    /**
     * 不完整定义的回调
     */
    private void startRxJava2() {
        //订阅者
        Action1<String> onNextAction = new Action1<String>(){  //Actionx:n参0返回
            //onNext()
            @Override
            public void call(String s) {
                Log.e(Tag, "Action1: " + s);
            }
        };
        Action1<Throwable> onErrorAciton = new Action1<Throwable>(){
            //onError();
            @Override
            public void call(Throwable throwable) {
                Log.e(Tag, "error");
            }
        };
        Action0 onCompletedAction = new Action0() {
            @Override
            public void call() {
                Log.e(Tag, "completed");
            }
        };

        Observable<String> observable = Observable.just("Hello", "Rx");
        observable.subscribe(onNextAction);
        observable.subscribe(onNextAction ,onErrorAciton);
        observable.subscribe(onNextAction, onErrorAciton, onCompletedAction);
    }

    private void startRxJava1() {
        //1.创建观察者
        Subscriber<String> subscriber1 = new Subscriber<String>() {
            @Override
            public void onCompleted() {
                Log.e(Tag, "1Completed!");
            }

            @Override
            public void onError(Throwable e) {
                Log.e(Tag, "1Error!");
            }

            @Override
            public void onNext(String s) {
                Log.e(Tag, "1item: + " + s);
            }
        };
        Subscriber<String> subscriber2 = new Subscriber<String>() {
            @Override
            public void onCompleted() {
                Log.e(Tag, "2Completed!");
            }

            @Override
            public void onError(Throwable e) {
                Log.e(Tag, "2Error!");
            }

            @Override
            public void onNext(String s) {
                Log.e(Tag, "2item: + " + s);
            }
        };
        Subscriber<String> subscriber3 = new Subscriber<String>() {
            @Override
            public void onCompleted() {
                Log.e(Tag, "3Completed!");
            }

            @Override
            public void onError(Throwable e) {
                Log.e(Tag, "3Error!");
            }

            @Override
            public void onNext(String s) {
                Log.e(Tag, "3item: + " + s);
            }
        };
        //2.创建被观察者
        Observable<String> observable1 = Observable.create(new Observable.OnSubscribe<String>(){  //creat()发方法创建实践序列
            @Override
            public void call(Subscriber<? super String> subscriber) {  //当 Observable 被订阅的时候，OnSubscribe 的 call() 方法会自动被调用
                //被观察者的计划表
                subscriber.onNext("Hello");
                subscriber.onNext("Hi");
                subscriber.onNext("Alpha");
                subscriber.onCompleted();
            }
        });

        Observable<String> observable2 = Observable.just("Hello", "Hi", "Beta");  //效果同上

        String[] words = {"Hello", "Hi", "Gamma"};
        Observable<String> observable3 = Observable.from(words);  //效果同上

        //3.订阅,？？一个观察者只能订阅一个被观察者？？
        observable1.subscribe(subscriber1);
        observable2.subscribe(subscriber2);
        observable3.subscribe(subscriber3);
    }

    private void ReadImgTest() {
        File folders = new File("");
        Observable.from(new File[]{folders})
                .flatMap(new Func1<File, Observable<File>>() {
                    @Override
                    public Observable<File> call(File file) {
                        return Observable.from(file.listFiles());
                    }
                })
                .filter(new Func1<File, Boolean>() {
                    @Override
                    public Boolean call(File file) {
                        return file.getName().endsWith(".png");
                    }
                })
                .map(new Func1<File, Bitmap>() {
                    @Override
                    public Bitmap call(File file) {
                        return getBimapFromFile(file);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Bitmap>() {
                    @Override
                    public void call(Bitmap bitmap) {

                        //imageCollectorView.addImge(bitmap);
                    }
                });
    }

    private Bitmap getBimapFromFile(File file) {
        return null;
    }
}


    //subscribe()核心代码
    //public Subscription subscribe(Subscriber subscriber) {
    //    subscriber.onStart();
    //    onSubscribe.call(subscriber);
    //    return subscriber;
    //}
